<template>
  <div class="container">
    <div class="projects-page">
      <h1 class="page-title">项目集市</h1>
      <p class="page-description highlight">支持项目定制，作业辅助。</p>
      
      <!-- 搜索筛选区域 -->
      <div class="projects-filter">
        <div class="filter-header">
          <div class="search-bar">
            <el-input 
              v-model="searchParams.keyword" 
              placeholder="搜索项目..." 
              clearable
              @keyup.enter="searchProjects"
              :prefix-icon="Search"
              class="search-input"
            />
          </div>
          
          <div class="button-group">
            <el-button 
              type="primary" 
              @click="searchProjects" 
              :loading="loading"
              class="search-button"
              :icon="Search"
            >
              搜索
            </el-button>
            
            <el-button 
              type="default" 
              @click="clearAll" 
              :disabled="loading"
              class="clear-button"
              :icon="Delete"
            >
              清除
            </el-button>
          </div>
        </div>
        
        <!-- 项目分类筛选 -->
        <div class="filter-categories">
          <el-radio-group v-model="searchParams.projectCategoryId" @change="searchProjects">
            <el-radio :label="null">全部</el-radio>
            <el-radio 
              v-for="category in categoryList" 
              :key="category.id" 
              :label="category.id"
            >
              {{ category.name }}
            </el-radio>
          </el-radio-group>
        </div>
        
        <!-- 技术栈筛选 -->
        <div class="filter-tech-stack" v-if="techStackOptions.length > 0">
          <span class="filter-label">技术栈：</span>
          <div class="tech-stack-filter">
            <el-tag 
              v-for="tech in techStackOptions" 
              :key="tech" 
              :class="{'tech-tag-selected': selectedTechStacks.includes(tech)}"
              @click="selectTechStack(tech)"
              size="default"
              :effect="selectedTechStacks.includes(tech) ? 'dark' : 'plain'"
              class="clickable-tag"
            >
              {{ tech }}
            </el-tag>
            <el-button 
              v-if="selectedTechStacks.length > 0" 
              size="small" 
              type="primary" 
              text 
              @click="clearTechStack"
            >
              清除筛选
            </el-button>
          </div>
        </div>
      </div>

      <!-- 项目列表展示区域 -->
      <el-empty v-if="!loading && projectList.length === 0" description="暂无相关项目" />
      
      <div v-else class="projects-container">
        <el-skeleton v-if="loading" :rows="5" animated />
        <template v-else>
          <div class="projects-grid">
            <el-card 
              v-for="project in projectList" 
              :key="project.id" 
              class="project-card"
              :body-style="{ padding: '0px' }"
              shadow="hover"
            >
              <RouterLink :to="`/project/${project.id}`" class="project-item-link">
                <div class="project-cover">
                <img :src="project.cover" :alt="project.name" />
              </div>
              <div class="project-content">
                <h3 class="project-title">{{ project.name }}</h3>
                <div class="project-category" v-if="getCategoryName(project.projectCategoryId)">
                  <el-tag size="small">{{ getCategoryName(project.projectCategoryId) }}</el-tag>
                </div>
                <p class="project-description">{{ project.description }}</p>
                <div class="project-tech-stack">
                  <span class="tech-stack-label">技术栈：</span>
                  <div class="tech-stack-tags">
                    <el-tag 
                      v-for="tech in project.techStack?.split(',')" 
                      :key="tech" 
                      size="small" 
                      type="info"
                      class="tech-tag"
                    >
                      {{ tech.trim() }}
                    </el-tag>
                  </div>
                </div>
                <div class="project-meta">
                  <span class="project-views">
                    <el-icon><View /></el-icon> {{ project.viewCount }} 浏览
                  </span>
                  <span class="project-price" v-if="project.price">
                    <el-icon><Money /></el-icon> <strong class="price-value">{{ project.price }}￥</strong>
                  </span>
                </div>
              </div>
              </RouterLink>
            </el-card>
          </div>
        </template>
      </div>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          background
          :layout="isMobile ? 'prev, pager, next, total' : 'prev, pager, next, sizes, jumper, total'"
          :total="total"
          v-model:current-page="searchParams.pageNum"
          v-model:page-size="searchParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { getProjectssList } from '../api/project.js'
import { getTagsList } from '../api/projectCategory.js'
import { View, Money, Search, Delete } from '@element-plus/icons-vue'
import { RouterLink } from 'vue-router'

// 数据定义
const projectList = ref([])
const categoryList = ref([])
const techStackOptions = ref([])
const total = ref(0)
const loading = ref(false)
const isMobile = ref(window.innerWidth <= 768)

// 搜索参数
const searchParams = ref({
  pageNum: 1,
  pageSize: 9,
  keyword: '',
  projectCategoryId: null,
  techStack: ''
})

// 选中的技术栈（多选）
const selectedTechStacks = ref([])

// 获取项目分类列表
const fetchCategories = async () => {
  try {
    const res = await getTagsList({
      pageNum: 1,
      pageSize: 100,
      keyword: ''
    })
    if (res.code === 200 && res.data) {
      categoryList.value = res.data.records
    }
  } catch (error) {
    console.error('获取项目分类失败:', error)
  }
}

// 获取项目列表
const fetchProjects = async () => {
  loading.value = true
  try {
    const res = await getProjectssList(searchParams.value)
    if (res.code === 200 && res.data) {
      projectList.value = res.data.records
      total.value = res.data.total
      searchParams.value.pageNum = res.data.current
      searchParams.value.pageSize = res.data.size
      
      // 提取所有项目的技术栈，用于筛选
      extractTechStacks()
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 提取所有技术栈选项
const extractTechStacks = () => {
  // 只在初始加载时提取技术栈，避免在筛选后改变技术栈选项
  if (techStackOptions.value.length === 0) {
    const techStacks = new Set()
    projectList.value.forEach(project => {
      if (project.techStack) {
        project.techStack.split(',').forEach(tech => {
          techStacks.add(tech.trim())
        })
      }
    })
    techStackOptions.value = Array.from(techStacks)
  }
}

// 根据分类ID获取分类名称
const getCategoryName = (categoryId) => {
  const category = categoryList.value.find(cat => cat.id === categoryId)
  return category ? category.name : ''
}

// 选择技术栈（多选）
const selectTechStack = (tech) => {
  const index = selectedTechStacks.value.indexOf(tech)
  if (index === -1) {
    // 添加技术栈
    selectedTechStacks.value.push(tech)
  } else {
    // 移除技术栈
    selectedTechStacks.value.splice(index, 1)
  }
  // 将选中的技术栈转换为逗号分隔的字符串
  searchParams.value.techStack = selectedTechStacks.value.join(',')
  // 选择技术栈后立即发送请求
  searchProjects()
}

// 清除技术栈筛选
const clearTechStack = () => {
  selectedTechStacks.value = []
  searchParams.value.techStack = ''
  searchProjects()
}

// 搜索项目
const searchProjects = () => {
  searchParams.value.pageNum = 1
  fetchProjects()
}

// 清除所有筛选条件
const clearAll = () => {
  searchParams.value.keyword = ''
  selectedTechStacks.value = []
  searchParams.value.techStack = ''
  searchParams.value.projectCategoryId = null // 直接设置为null值，对应全部选项
  searchProjects()
}

// 分页处理
const handleSizeChange = (size) => {
  searchParams.value.pageSize = size
  fetchProjects()
}

const handleCurrentChange = (page) => {
  searchParams.value.pageNum = page
  fetchProjects()
}

// 检测窗口大小变化
const handleResize = () => {
  isMobile.value = window.innerWidth <= 768
}

// 页面加载时获取数据
onMounted(() => {
  // 设置projectCategoryId为null，以选中"全部"选项
  searchParams.value.projectCategoryId = null
  fetchCategories()
  fetchProjects()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.project-page {
  /* padding: 2rem 0; */
  text-align: left;
}

.page-title {
  font-size: 2.5rem;
  margin-bottom: 0.5rem;
}

.page-description {
  font-size: 1.125rem;
  margin-bottom: 2rem;
  color: #555;
}

.projects-filter {
  margin-bottom: 2rem;
  /* padding: 1.5rem; */
  background-color: var(--color-background-soft);
  border-radius: 8px;
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
}

.filter-header {
  display: flex;
  gap: 1rem;
  margin-bottom: 1.5rem;
  align-items: center;
  max-width: 100%;
  justify-content: flex-start;
}

.search-bar {
  flex: 1;
  max-width: 600px;
}

.search-input :deep(.el-input__wrapper) {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  border-radius: 8px;
  background-color: var(--color-background);
  border: 1px solid var(--el-border-color);
}

.search-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border-color: var(--el-border-color-hover);
}

.search-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 4px 12px rgba(var(--el-color-primary-rgb), 0.15);
  border-color: var(--el-color-primary);
}

.search-input :deep(.el-input__inner) {
  height: 44px;
  font-size: 15px;
}

.button-group {
  display: flex;
  gap: 0.5rem;
  flex-shrink: 0;
}

.search-button,
.clear-button {
  height: 44px;
  padding: 0 20px;
  font-size: 15px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.search-button:hover,
.clear-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.filter-categories {
  margin-bottom: 1.5rem;
  text-align: left;
}

.filter-tech-stack {
  display: flex;
  align-items: center;
  gap: 1rem;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.tech-stack-filter {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  align-items: center;
  justify-content: flex-start;
}

.clickable-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.clickable-tag:hover {
  transform: translateY(-2px);
}

.tech-tag-selected {
  font-weight: bold;
}

.filter-label {
  font-weight: 600;
  color: var(--color-text);
}

.projects-container {
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
}

.projects-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 1.5rem;
  text-align: left;
}

.project-card {
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.project-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.project-item-link {
  display: block;
  text-decoration: none;  /* 去掉下划线 */
  color: inherit;
  height: 100%;
}

.project-item-link:hover {
  text-decoration: none;  /* 确保悬停时也没有下划线 */
}

.project-cover {
  height: 180px;  /* 增加图片高度 */
  overflow: hidden;
  border-radius: 8px 8px 0 0;  /* 顶部圆角 */
}

.project-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;  /* 平滑过渡效果 */
}

.project-card:hover .project-cover img {
  transform: scale(1.08);  /* 轻微放大效果 */
}

.project-content {
  padding: 0.75rem;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.project-title {
  font-size: 1rem;
  font-weight: 600;
  margin-bottom: 0.3rem;
  color: var(--color-heading);
}

.project-category {
  margin-bottom: 0.5rem;
}

.project-description {
  margin-bottom: 0.6rem;
  color: var(--color-text);
  line-height: 1.3;
  font-size: 0.85rem;
  flex: 1;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.project-tech-stack {
  margin-bottom: 0.6rem;
}

.tech-stack-label {
  font-weight: 600;
  font-size: 0.8rem;
  color: var(--color-text-light);
  margin-bottom: 0.3rem;
  display: block;
}

.tech-stack-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.tech-tag {
  margin-right: 0.3rem;
  margin-bottom: 0.3rem;
  font-size: 0.8rem;
}

.project-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: var(--color-text-light);
  font-size: 0.8rem;
  margin-top: auto;
  padding-top: 0.75rem;
  border-top: 1px dashed var(--el-border-color-lighter);
}

.project-views,
.project-price {
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.project-price {
  font-weight: 500;
  color: #f56c6c;
}

.price-value {
  font-size: 1.2rem;
  color: #f56c6c;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin: 2rem 0;
}

@media (max-width: 768px) {
  .page-title {
    font-size: 2rem;
    margin-bottom: 0.3rem;
  }
  
  .page-description {
    font-size: 1rem;
    margin-bottom: 1.5rem;
  }
  
  
  .filter-header {
    flex-direction: column;
    gap: 0.75rem;
  }
  
  .search-bar {
    width: 100%;
  }
  
  .button-group {
    width: 100%;
    justify-content: space-between;
  }
  
  .search-button,
  .clear-button {
    flex: 1;
  }
  
  .filter-categories {
    margin-bottom: 1rem;
    overflow-x: auto;
    padding-bottom: 0.5rem;
    text-align: left;
  }
  
  .filter-categories .el-radio-group {
    display: flex;
    flex-wrap: nowrap;
    overflow-x: auto;
    padding-bottom: 0.3rem;
    justify-content: flex-start;
  }
  
  .filter-categories .el-radio {
    flex-shrink: 0;
    margin-right: 0.8rem;
  }
  
  .filter-tech-stack {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
    text-align: left;
  }
  
  .tech-stack-filter {
    width: 100%;
    justify-content: flex-start;
  }
  
  .projects-grid {
    grid-template-columns: 1fr;
    gap: 1rem;
  }
  
  .project-card {
    margin-bottom: 0.5rem;
  }
  
  .project-content {
    padding: 0.6rem;
  }
  
  .project-title {
    font-size: 0.95rem;
  }
  
  .project-description {
    font-size: 0.8rem;
    -webkit-line-clamp: 3;
  }
  
  .tech-stack-tags {
    gap: 0.3rem;
  }
  
  .tech-tag {
    margin-right: 0.2rem;
    margin-bottom: 0.2rem;
    font-size: 0.75rem;
  }
  
  .pagination-container {
    margin-top: 1.5rem;
  }
  
  .pagination-container .el-pagination {
    flex-wrap: wrap;
    justify-content: center;
    row-gap: 0.5rem;
  }
}
</style>